#!/bin/bash

# ==================== 审计追踪系统构建和测试脚本 ====================
# 功能：自动编译和测试所有增强功能 (Linux/Mac版本)
# 版本：1.0.0

echo "==================== 审计追踪系统构建和测试脚本 ===================="
echo "功能：自动编译和测试所有增强功能"
echo "版本：1.0.0"
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 检查Qt环境
echo -e "${BLUE}🔍 检查Qt开发环境...${NC}"
if ! command -v qmake &> /dev/null; then
    echo -e "${RED}❌ 错误：未找到qmake，请确保Qt开发环境已正确安装${NC}"
    exit 1
fi
echo -e "${GREEN}✅ Qt环境检查通过${NC}"

# 检查编译器
echo -e "${BLUE}🔍 检查编译器...${NC}"
if ! command -v make &> /dev/null; then
    echo -e "${RED}❌ 错误：未找到make编译器${NC}"
    exit 1
fi
echo -e "${GREEN}✅ 编译器检查通过${NC}"

# 创建构建目录
echo -e "${BLUE}📁 创建构建目录...${NC}"
mkdir -p build
cd build

# 编译演示程序
echo -e "${BLUE}🔨 编译功能演示程序...${NC}"
qmake ../demo.pro
if [ $? -ne 0 ]; then
    echo -e "${RED}❌ qmake失败${NC}"
    cd ..
    exit 1
fi

make
if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 编译失败${NC}"
    cd ..
    exit 1
fi
echo -e "${GREEN}✅ 演示程序编译成功${NC}"

# 编译测试程序
echo -e "${BLUE}🔨 编译测试程序...${NC}"
cat > test.pro << EOF
QT += core
CONFIG += console c++17
TARGET = SystemTester
TEMPLATE = app
SOURCES += ../run_tests.cpp ../permissionmanager.cpp ../dataexporter.cpp ../pluginsystem.cpp ../auditlogger.cpp ../databasehandler.cpp
HEADERS += ../permissionmanager.h ../dataexporter.h ../pluginsystem.h ../auditlogger.h ../databasehandler.h ../AuditEntry.h
EOF

qmake test.pro
if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 测试程序qmake失败${NC}"
    cd ..
    exit 1
fi

make
if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 测试程序编译失败${NC}"
    cd ..
    exit 1
fi
echo -e "${GREEN}✅ 测试程序编译成功${NC}"

# 运行自动化测试
echo -e "${BLUE}🧪 运行自动化功能测试...${NC}"
echo ""
./SystemTester
if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 测试执行失败${NC}"
    cd ..
    exit 1
fi

echo ""
echo -e "${GREEN}🎉 所有测试完成！${NC}"
echo ""
echo -e "${YELLOW}📋 可用程序：${NC}"
echo "   - ./AuditTrailSystemDemo : 功能演示程序"
echo "   - ./SystemTester         : 自动化测试程序"
echo ""

# 询问是否运行演示程序
read -p "是否运行功能演示程序？(y/n): " choice
if [[ $choice == [Yy]* ]]; then
    echo -e "${BLUE}🚀 启动功能演示程序...${NC}"
    ./AuditTrailSystemDemo &
fi

cd ..
echo -e "${GREEN}✅ 构建和测试完成！${NC}"